package com.mac.hosp_pre.user.api;

import com.mac.hosp_pre.except.ResultCodeEnum;
import com.mac.hosp_pre.reply.R;
import com.mac.hosp_pre.user.entity.Patient;
import com.mac.hosp_pre.user.model.req.PatientReqDto;
import com.mac.hosp_pre.user.model.resp.PatientRespDto;
import com.mac.hosp_pre.user.service.PatientService;
import com.mac.hosp_pre.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Tag(name = "门户就诊人接口")
@RestController
@RequestMapping("/api/user/patient")
public class PatientApiController {

    @Autowired
    private PatientService patientService;

    @Operation(summary = "获取就诊人列表")
    @GetMapping("/findAll")
    public R findAll(HttpServletRequest request) {
        //获取当前登录用户id
        Long userId = JwtUtil.getUserId(request);
        List<PatientRespDto> respDtos = patientService.findAllUserId(userId);
        return R.success(respDtos);
    }

    @Operation(summary = "添加就诊人")
    @PostMapping("/save")
    public R savePatient(@RequestBody PatientReqDto patient, HttpServletRequest request) {
        //获取当前登录用户id
        Long userId = JwtUtil.getUserId(request);
        Patient pat = new Patient();
        BeanUtils.copyProperties(patient, pat);
        pat.setUserId(userId);
        patientService.save(pat);
        return R.success();
    }

    @Operation(summary = "根据id获取就诊人信息")
    @GetMapping("/get/{id}")
    public R getPatient(@PathVariable Long id) {
        PatientRespDto respDto = patientService.getPatientId(id);
        return R.success(respDto);
    }

    @Operation(summary = "修改就诊人")
    @PostMapping("/update")
    public R updatePatient(@RequestBody PatientReqDto patient) {
        if (patient.getId() == null){
            return R.error(ResultCodeEnum.PARAM_EMPTY_ERROR.getCode(), "id不能为空");
        }
        Patient pat = new Patient();
        BeanUtils.copyProperties(patient, pat);
        patientService.updateById(pat);
        return R.success();
    }

    @Operation(summary = "删除就诊人")
    @DeleteMapping("/remove/{id}")
    public R removePatient(@PathVariable Long id) {
        Patient patient = patientService.getById(id);
        if (patient == null){
            return R.error(ResultCodeEnum.NOT_EXISTS_ERROR);
        }
        patientService.removeById(id);
        return R.success();
    }
}
